/*
 * TendChartFrame.java
 *
 * Created on Jan 15, 2012, 11:44:20 PM
 */
package gui;

/**
 *
 * @author suzann
 */
import chart.TendChartPanel;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.DefaultFontMapper;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.toedter.calendar.*;
import db.DatabaseManager;
import db.entity.PadLife;
import db.entity.TaperMap;
import db.entity.WCSDataInterface;
import excelexporter.ExcelExporter;
import excelexporter.TendChartBean;

import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

import util.ErrorMessage;
import util.PropertiesLoader;
import util.SimpleFileFilter;

public class TendChartFrame extends javax.swing.JFrame {

    /** Creates new form TendChartFrame */
    public TendChartFrame() {
        //initialize variables
        _instance = this;
        
    	dm = new DatabaseManager();
        tcPnl = new TendChartPanel();
        
        initComponents();
        setInitData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        rbgTitle = new javax.swing.ButtonGroup();
        jPanel2 = new javax.swing.JPanel();
        jbtDisplay = new javax.swing.JButton();
        jcbPolisher = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jdcFromDate = new JDateChooser(null, null, null, new JSpinnerDateEditor());
        jdcToDate = new JDateChooser(null, null, null, new JSpinnerDateEditor());
        jPanel3 = new javax.swing.JPanel();
        jrbTTV = new javax.swing.JRadioButton();
        jrbTIR = new javax.swing.JRadioButton();
        jrbTaper = new javax.swing.JRadioButton();
        jrbRemoval = new javax.swing.JRadioButton();
        jrbSTIR = new javax.swing.JRadioButton();
        dateFrom = new Date();
        sdmFrom = new SpinnerDateModel(dateFrom, null, null, 11);
        jspFromTime = new javax.swing.JSpinner(sdmFrom);
        dateTo = new Date();
        sdmTo = new SpinnerDateModel(dateTo, null, null, 11);
        jspToTime = new javax.swing.JSpinner(sdmTo);
        jbtExcel = new javax.swing.JButton();
        jbtPDF = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(1024, 688));

        jPanel2.setPreferredSize(new java.awt.Dimension(764, 150));
        jPanel2.setRequestFocusEnabled(false);

        jbtDisplay.setText("Display");
        jbtDisplay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDisplayActionPerformed(evt);
            }
        });

        jcbPolisher.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A_1L", "A_1R", "A_2L", "A_2R", "A_3L", "A_3R", "A_4L", "A_4R", "A_5L", "A_5R", "A_6L", "A_6R", "A_7L", "A_7R" }));

        jLabel2.setText("From");

        jLabel1.setText("Polisher");

        jLabel3.setText("To");

        rbgTitle.add(jrbTTV);
        jrbTTV.setText("TTV");
        jrbTTV.setActionCommand("TTV");

        rbgTitle.add(jrbTIR);
        jrbTIR.setSelected(true);
        jrbTIR.setText("TIR");
        jrbTIR.setActionCommand("TIR");

        rbgTitle.add(jrbTaper);
        jrbTaper.setText("Taper");
        jrbTaper.setActionCommand("Taper");

        rbgTitle.add(jrbRemoval);
        jrbRemoval.setText("Removal");
        jrbRemoval.setActionCommand("Removal");

        rbgTitle.add(jrbSTIR);
        jrbSTIR.setText("STIR");
        jrbSTIR.setActionCommand("STIR");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jrbTTV)
                        .addComponent(jrbTIR))
                    .addComponent(jrbRemoval)
                    .addComponent(jrbTaper)
                    .addComponent(jrbSTIR))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jrbTIR)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbTTV)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbSTIR)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbRemoval)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jrbTaper)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        deFrom = new JSpinner.DateEditor(jspFromTime, "hh:mm a");
        jspFromTime.setEditor(deFrom);

        deTo = new JSpinner.DateEditor(jspToTime, "hh:mm a");
        jspToTime.setEditor(deTo);

        jbtExcel.setText("Export to Excel");
        jbtExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtExcelActionPerformed(evt);
            }
        });

        jbtPDF.setText("Export to PDF");
        jbtPDF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtPDFActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbPolisher, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jbtDisplay)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtExcel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtPDF))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jdcToDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jdcFromDate, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jspToTime, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jspFromTime, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(253, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jspFromTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(jcbPolisher, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                            .addComponent(jdcFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jdcToDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jspToTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(27, 27, 27)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtDisplay)
                            .addComponent(jbtExcel)
                            .addComponent(jbtPDF))))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-904)/2, (screenSize.height-609)/2, 904, 609);
    }// </editor-fold>
    /****************************************************************************
     * Action Listeners
     ****************************************************************************/
    
    private void jbtDisplayActionPerformed(java.awt.event.ActionEvent evt) {                                           
        showTendChart();
    }                                          

    private void jbtExcelActionPerformed(java.awt.event.ActionEvent evt) {                                         
        exportToExcel();
    }                                        

    private void jbtPDFActionPerformed(java.awt.event.ActionEvent evt) {
        exportToPDF();
    }
    /****************************************************************************
     * Internal Operations
     ****************************************************************************/
    /**
     * This method sets the initial data for Tend Chart Display at first launch.
     * @param 
     */
    private void setInitData()
    {
        Calendar today = Calendar.getInstance();
        
        Calendar yesterday = Calendar.getInstance();
        yesterday.setTimeInMillis(today.getTimeInMillis() - 86400000L);
        
        this.jdcToDate.setDate(today.getTime());
        this.jdcFromDate.setDate(yesterday.getTime());
        
        //default value of inputs
        graphType = TendChartPanel.GRAPH_TIR;         
        jcbPolisher.setSelectedIndex(-1);
        jrbTIR.setSelected(true);
    }
    
    /**
     * This method get component values and show the Tend Chart.
     * @param 
     */    
    
    private void showTendChart()
    {
        if(!validateInput())
    		return ;
        
        /*get the inputs*/
        //1. Polisher Arms
        String polisherArms = "";;
        polisherArms = jcbPolisher.getSelectedItem().toString();
        System.out.println("Polisher : " + polisherArms);
        
        //2. Radio Button
        String actionCommand = rbgTitle.getSelection().getActionCommand();
        System.out.println("Action command : " + actionCommand);
        
        //3. From DateTime
        Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(TendChartFrame.this.sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(TendChartFrame.this.jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();
        System.out.println("From date =" + fromDateTime.getTime());

        //4. To DateTime
        Calendar toTime = Calendar.getInstance();
        toTime.setTime(TendChartFrame.this.sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(TendChartFrame.this.jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
        System.out.println("to date =" + toDateTime.getTime());
        
        //Check the radio button
        String title = null;
        
        String dcElement = getDCMap(polisherArms);
        String stationID = "0"+polisherArms.substring(2, 3);
        
        if (actionCommand.equals("TTV")) 
        {
            title = "TTV Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "TTV");
            graphType = TendChartPanel.GRAPH_TTV;
        }
        else if (actionCommand.equals("Taper")) 
        {
            title = "Taper Capability - " + polisherArms;
            graphType = TendChartPanel.GRAPH_TAPERSPC;
        }
        else if (actionCommand.equals("TIR")) 
        {
            title = "TIR Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "TIR");
            graphType = TendChartPanel.GRAPH_TIR;
        }
        else if (actionCommand.equals("STIR")) 
        {
            title = "STIR Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "STIR");
            graphType = TendChartPanel.GRAPH_STIR;
        }
        else if (actionCommand.equals("Removal")) 
        {
            title = "Removal Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "PREMDS");
            graphType = TendChartPanel.GRAPH_REMOVAL;
        }

//        dcElement = dcElement + polisherArms.substring(0, 3);
        
//        String stationID = "";
//        int lastIndex = polisherArms.length();
        
//        if (polisherArms.endsWith("L"))
//        {
//            dcElement = dcElement + "L";
//            stationID = polisherArms.substring(lastIndex-2, lastIndex-1);
//        }
            
//        else 
//        {
//            dcElement = dcElement + 'R';
//            stationID = polisherArms.substring(lastIndex-2, lastIndex-1);
//        }
        
//        stationID = "0" + stationID;
//              
        System.out.println("DCELEMENT: "+dcElement);
        //Determine the query using the graphType
        if (graphType == TendChartPanel.GRAPH_TTV)
        sList = dm.listTTVByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_TAPERSPC)
        sList = dm.listTaperSpcByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_TIR)
        sList = dm.listTIRByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_STIR)
        sList = dm.listSTIRByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_REMOVAL)
        sList = dm.listRemovalByDCElement(dcElement, startDate, endDate );
        
        
        pList = dm.listPadlifeByStationNameDate(stationID, startDate, endDate);
        
        System.out.println("sList: "+sList.size());
        System.out.println("pList: "+pList.size());
        
        tcPnl.loadData(graphType, title, ((List<WCSDataInterface>)sList), (List<PadLife>)pList);
                
        //show the chart
        tcPnl.setVisible(true);
        this.getContentPane().add(tcPnl,BorderLayout.CENTER);
        this.invalidate();
        this.validate();
    }
        
    private boolean validateInput()
    {    	
    	//VALIDATE POLISHER ARM
    	if(jcbPolisher.getSelectedItem() == null)
    	{
    		String errMsg = "Please select a Polisher Arm";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// VALIDATE BLANK FIELDS
    	boolean blankField = false;
    	String blankField_str = "";
    	if(jdcFromDate.getDate()==null)
    	{
    		blankField_str += "jdcFromDate;";
    		blankField = true;
    	}    	
    	if(jdcToDate.getDate()==null)
    	{
    		blankField_str += "jdcToDate;";
    		blankField = true;
    	}    	
    	
    	if(blankField)
    	{
    		String errMsg = "Please fill in the following field: \n" + blankField_str;
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// VALIDATE FROM DATE BEFORE TO DATE
    	Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();

        Calendar toTime = Calendar.getInstance();
        toTime.setTime(sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
		
    	if(! startDate.before(endDate))
    	{
    		String errMsg = "From Date should be a date before To Date.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// Difference between From Data and To Date should be within range in properties file
    	int difference = toDateTime.get(Calendar.DAY_OF_YEAR) - fromDateTime.get(Calendar.DAY_OF_YEAR);
    	
    	if (difference > PropertiesLoader.getTendChartMaxRange())
    	{
    		String errMsg = "To Date cannot be "+PropertiesLoader.getTendChartMaxRange()+" days after From Date.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}    	
    	
    	return true;
    }
    
    /** 
     * THIS SECTION HANDLES THE EXPORT TO EXCEL FUNCTIONALITY,
     * INCLUDING ALL THE ADDITIONAL METHODS AND INNER CLASS NEEDED
     *   
     **/ 
     private void exportToExcel()
    {
    	if(!validateInput())
    		return ;
    	
    	/*get the inputs*/
        //1. Polisher Arms
        String polisherArms = "";;
        polisherArms = jcbPolisher.getSelectedItem().toString();
        System.out.println("Polisher : " + polisherArms);
        
        //2. Radio Button
        String actionCommand = rbgTitle.getSelection().getActionCommand();
        System.out.println("Action command : " + actionCommand);
        
        //3. From DateTime
        Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(TendChartFrame.this.sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(TendChartFrame.this.jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();
        System.out.println("From date =" + fromDateTime.getTime());

        //4. To DateTime
        Calendar toTime = Calendar.getInstance();
        toTime.setTime(TendChartFrame.this.sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(TendChartFrame.this.jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
        System.out.println("to date =" + toDateTime.getTime());
                
        //Check the radio button
        String title = null;
        
        String dcElement = getDCMap(polisherArms);
        String stationID = polisherArms.substring(2, 3);
        
        if (actionCommand.equals("TTV")) 
        {
            title = "TTV Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "TTV");
            graphType = TendChartPanel.GRAPH_TTV;
        }
        else if (actionCommand.equals("Taper")) 
        {
            title = "Taper Capability - " + polisherArms;
            graphType = TendChartPanel.GRAPH_TAPERSPC;
        }
        else if (actionCommand.equals("TIR")) 
        {
            title = "TIR Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "TIR");
            graphType = TendChartPanel.GRAPH_TIR;
        }
        else if (actionCommand.equals("STIR")) 
        {
            title = "STIR Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "STIR");
            graphType = TendChartPanel.GRAPH_STIR;
        }
        else if (actionCommand.equals("Removal")) 
        {
            title = "Removal Capability - " + polisherArms;
            dcElement = dcElement.replace("TP", "PREMDS");
            graphType = TendChartPanel.GRAPH_REMOVAL;
        }
        
        //Determine the query using the graphType
        if (graphType == TendChartPanel.GRAPH_TTV)
        sList = dm.listTTVByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_TAPERSPC)
        sList = dm.listTaperSpcByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_TIR)
        sList = dm.listTIRByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_STIR)
        sList = dm.listSTIRByDCElement(dcElement, startDate, endDate );

        else if (graphType == TendChartPanel.GRAPH_REMOVAL)
        sList = dm.listRemovalByDCElement(dcElement, startDate, endDate );
        
        pList = dm.listPadlifeByStationNameDate(stationID, startDate, endDate);
        System.out.println("sList: "+sList.size());
        System.out.println("pList: "+pList.size());
             
        
        double average, stdDev, value1, value2, value3, value4;
		int index;
		DecimalFormat df = new DecimalFormat("#.##");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:MM");
	
		ArrayList<TendChartBean> beanLS = new ArrayList<TendChartBean>();
		
		for(Object sItem_obj : sList)
		{
			if(!(sItem_obj instanceof WCSDataInterface))
				continue;
			WCSDataInterface sItem = (WCSDataInterface) sItem_obj;
			
			value1 = sItem.getValue1();
			value2 = sItem.getValue2();
			value3 = sItem.getValue3();
			value4 = sItem.getValue4();
			
			average = (value1 + value2 + value3 + value4) /4;
			stdDev = java.lang.Math.sqrt( 
						(java.lang.Math.pow((value1 - average), 2) + 
						java.lang.Math.pow((value2 - average), 2) + 
						java.lang.Math.pow((value3 - average), 2) + 
						java.lang.Math.pow((value4 - average), 2) 
						) / 4
					);

			TendChartBean bean = new TendChartBean();
			bean.setdCElement(sItem.getDCElement());
			bean.setLotID(sItem.getLotID());
			bean.setLotID(sItem.getLotID());
			bean.setSpcStartDate(sItem.getSpcStartDate());			
			
			bean.setAverage(average);
			bean.setStandardDev(stdDev);
			
			beanLS.add(bean);
		}	
		new ExcelExporter().generateTendChartBean(beanLS);		
    }
    
    
    ArrayList<String> leftTaper = null;
    ArrayList<String> rightTaper = null;
    
    private String getDCMap(String polisherArm)
    {
    	if(leftTaper == null || rightTaper == null)
    		createDCMap();
    	
    	int stationNo = Integer.parseInt(polisherArm.substring(2, 3));
    	String leftRightInd = polisherArm.substring(3);
    	if(leftRightInd.toUpperCase().equals("L"))
    		return leftTaper.get(stationNo-1);
    	else if (leftRightInd.toUpperCase().equals("R"))
    		return rightTaper.get(stationNo-1);
    	
    	return null;
    }
    
    public static void updateDCMap()
    {
    	if(_instance == null)
    		_instance = new TendChartFrame();
    	
    	_instance.createDCMap();
    }
    
    private void createDCMap()
    {
    	leftTaper = new ArrayList<String>(7);
		for(int i=0; i<7; i++)
			leftTaper.add("");

		rightTaper = new ArrayList<String>(7);
		for(int i=0; i<7; i++)
			rightTaper.add("");
		
    	List<TaperMap>taperMapList = new DatabaseManager().listTaperMap();
		int index=0;
		for(TaperMap mapItem : taperMapList)
		{
			index = Integer.parseInt(mapItem.getStationName());
			if(index > 7)
				continue;
			
			leftTaper.set(index-1, mapItem.getLeftTaper());
			rightTaper.set(index-1, mapItem.getRightTaper());				
		}
    }
/**
 * END EXPORT TO EXCEL FUNCTIONALITY    
 * 
 **/
    
    private void exportToPDF() {
    	JFileChooser fc = new JFileChooser();
    	fc.setFileSelectionMode(0);
    	fc.setFileFilter(new SimpleFileFilter("pdf"));
    	
    	int returnVal = fc.showSaveDialog(this);
    	if (returnVal == 0) {
    		File file = fc.getSelectedFile();
    		
    		String path = file.getAbsolutePath();
    		
    		if (!path.endsWith(".pdf")) {
    		path = path + ".pdf";
    		}
    		
    		String finalPath = path;
    		try {
    			OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(finalPath)));
    			Rectangle pagesize = new Rectangle(842, 595);
    			Document document = new Document(pagesize, 50.0F, 50.0F, 50.0F, 50.0F);
    			try {
    				PdfWriter writer = PdfWriter.getInstance(document, out);
    				document.addAuthor("JFreeChart");
    				document.addSubject("Demonstration");
    				document.open();
    				PdfContentByte cb = writer.getDirectContent();
    				PdfTemplate tp = cb.createTemplate(842, 595);
    				Graphics2D g2 = tp.createGraphics(842, 595, new DefaultFontMapper());
    				Rectangle2D r2D = new Rectangle2D.Double(0.0D, 0.0D, 842, 595);

    				tcPnl.drawChart(g2, r2D);

    				g2.dispose();
    				cb.addTemplate(tp, 0.0F, 0.0F);
    			} catch (DocumentException de) {
    				System.err.println(de.getMessage());
    			}
    			document.close();
    			out.close();
    			
    			JOptionPane.showMessageDialog(null, "Graph successfully exported to PDF.", "Export Successfully", JOptionPane.PLAIN_MESSAGE);
    		}
    		catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TendChartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TendChartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TendChartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TendChartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TendChartFrame().setVisible(true);
            }
        });
    }
    /****************************************************************************
     * INTERNAL OPERATIONS : THE FRAME
     ****************************************************************************/
    
    /**
     * Prompts up a confirmation dialog to confirm the exit action.
     * Upon confirmation, dispose the frame.
     */
    private void onExit()
    {
        //remove the TendChart Panel
        tcPnl.setVisible(false);
        this.invalidate();
        this.validate();
        
        //reset all the values to default
        setInitData();
        
        //dispose the frame
        this.dispose();
    }
    
    /**
     * This is a hack for user to click on the 'x' button on window
     */
    protected void processWindowEvent(WindowEvent we)
    {
            if(we.getID() == WindowEvent.WINDOW_CLOSING)
                    onExit();
    }
    /****************************************************************************
     *  THE VARIABLES
     ****************************************************************************/
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jbtDisplay;
    private javax.swing.JButton jbtExcel;
    private javax.swing.JButton jbtPDF;
    private javax.swing.JComboBox jcbPolisher;
    private com.toedter.calendar.JDateChooser jdcFromDate;
    private com.toedter.calendar.JDateChooser jdcToDate;
    private javax.swing.JRadioButton jrbRemoval;
    private javax.swing.JRadioButton jrbSTIR;
    private javax.swing.JRadioButton jrbTIR;
    private javax.swing.JRadioButton jrbTTV;
    private javax.swing.JRadioButton jrbTaper;
    Date dateFrom;
    SpinnerDateModel sdmFrom;
    JSpinner.DateEditor deFrom;
    private javax.swing.JSpinner jspFromTime;
    Date dateTo;
    SpinnerDateModel sdmTo;
    JSpinner.DateEditor deTo;
    private javax.swing.JSpinner jspToTime;
    private javax.swing.ButtonGroup rbgTitle;
    // End of variables declaration
    private DatabaseManager dm;
    private TendChartPanel tcPnl;
    private int graphType;
    private List sList, pList;
    private static TendChartFrame _instance;
}
